package arrays;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LiangMu
 * @version \$Id: Main.java, v 0.1, 2022年12月10日 14:10 LiangMu Exp $$
 */
public class Main {
    public static List<Integer> findMatch(String[] truckTracks, String expectCities) {
        if (expectCities.length() <= 0) {
            return null;
        }
        Set<String> expSet = Arrays.stream(expectCities.split("")).collect(Collectors.toSet());
        List<Integer> result = new ArrayList<>();
        int len = truckTracks.length;
        for (int i = 0; i < len; ++i) {
            String str = truckTracks[i];
            Set<String> collect = Arrays.stream(str.split("")).collect(Collectors.toSet());
            if (collect.containsAll(expSet)) {
                result.add(i);
            }
        }
        return result;
    }

    public static Integer findMinMatch(String[] truckTracks, String expectCities) {
        if (expectCities.length() <= 0) {
            return null;
        }
        int result = Integer.MAX_VALUE;
        int len = truckTracks.length;
        int res = -1;
        for (int i = 0; i < len; ++i) {
            String str = truckTracks[i];
            if (str.length() < expectCities.length()) continue;
            Integer fun = fun(str, expectCities);
            if (result > fun) {
                res = i;
                result = fun;
            }
        }
        return res;
    }

    public static void main(String[] args) {
//        List<Integer> cde = findMatch(new String[]{"ABEDC", "BCDE", "BC", "AD"}, "CDE");
        Integer cde1 = findMinMatch(new String[]{"ZXCVBNQWEABDEFC", "BCDAFECFBE", "BC", "AD"}, "CDE");
//        System.out.println(cde);
        System.out.println(cde1);
    }

    public static Integer fun(String str, String subStr) {
        Set<String> collect = Arrays.stream(subStr.split("")).collect(Collectors.toSet());
        String[] split = str.split("");
        int len = split.length;
        int result = Integer.MAX_VALUE;
        for (int i = 0; i < len; ++i) {
            String s = split[i];
            if (collect.contains(s)) {
                int count = 0;
                Set<String> clone = new HashSet<>(collect.size());
                clone.addAll(collect);
                for (int j = i; j < split.length; ++j) {
                    count++;
                    String s1 = split[j];
                    if (clone.contains(s1)) {
                        if (collect.remove(s1)) break;
                        if (collect.isEmpty()) break;
                    }
                }
                i += count;
                result = Math.min(count, result);
            }
        }
        return result;
    }
}
